package com.goldgov.commylog.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gtiles.core.module.auditlog.bean.AuditLogBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goldgov.auditlog.service.AuditLog;
import com.goldgov.auditlog.service.IAuditLogService;
import com.goldgov.commylog.service.Commylog;
import com.goldgov.commylog.service.CommylogQuery;
import com.goldgov.commylog.service.CommylogService;
import com.goldgov.kcloud.core.json.JsonObject;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.ms.adapter.call.RemoteCallService;
import com.goldgov.securityworkbench.attachment.AttachementBean;
import com.goldgov.utils.DataUtil;
import com.goldgov.utils.DateUtil;
import com.goldgov.utils.IpUtil;
import com.goldgov.utils.PropertyUtil;
import com.goldgov.utils.UrlUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/portal/commylog")
@Api("工作日志服务接口")
public class CommylogForPortalController {

	@Autowired
	private CommylogService service;
	
	@Autowired
	private RemoteCallService remoteCallService;
	
	@Autowired
	private IAuditLogService auditLogService;
	
	@GetMapping("/preAddCommylog")
	@ApiOperation(value = "预新增工作日志", notes ="查询日志ID")
	public JsonSuccessObject<Commylog> preAddCommylog(Commylog obj,HttpServletRequest request){
		obj = service.getCommylogID();
		JsonSuccessObject<Commylog> returnResult = new JsonSuccessObject<>(obj);
		return returnResult;
	}
	
	@ResponseBody
	@PostMapping
	@ApiOperation(value = "新增工作日志", notes ="")
	public JsonObject<Object> addCommylog(Commylog obj, HttpServletRequest request,HttpServletResponse response,Model model) throws IOException {
		LoginAuthUser u=LoginAuthUser.getUser(request);
		obj.setUserID(u.getEntityID());
		obj.setUserName(u.getName());
		obj.setAuditState(CommylogQuery.AUDIT_STATE_ONE);
		obj.setActiveState(CommylogQuery.ACTIVE_STATE_YES);
		if(obj.getCreateDate()==null||obj.getCreateDate().equals("")) {
			obj.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		}else {
			Date date = DateUtil.strToDate(obj.getCreateDate());
			obj.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
		}
		service.addCommylog(obj);
		String operateContent = "commylogID=" + obj.getCommylogID() + ",commylogValue=" + obj.getCommylogValue()
		+ ",createDate=" + obj.getCreateDate();
		AuditLog auditLog = new AuditLog();
		auditLog.setOperateType("Save");
		auditLog.setModuleName("工作日志");
		auditLog.setOperateName("新增");
		auditLog.setOperateTime(new Date());
		auditLog.setOperateUserId(u.getEntityID());
		auditLog.setOperateUserName(u.getName());
		auditLog.setOperateState(AuditLogBean.OPERATE_STATE_SUCCESS);
		auditLog.setOperateIp(IpUtil.getIpAddress(request));
		auditLog.setOperateUrl(request.getRequestURL().toString());
		auditLog.setOperateContent(operateContent);
		auditLogService.addAuditLog(auditLog);
		return JsonSuccessObject.SUCCESS;
	}
	@RequestMapping("/listCommylog")
	@ApiOperation(value = "查询多条日志", notes ="日志列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchUserID", value = "日志用户id查询条件", paramType = "query"),
		@ApiImplicitParam(name = "searchAuditState", value = "日志状态查询条件", paramType = "query"),
		@ApiImplicitParam(name = "searchCreateDateBegin", value = "日志查询开始时间", paramType = "query"),
		@ApiImplicitParam(name = "searchCreateDateEnd", value = "日志查询结束时间", paramType = "query")})
	public JsonQueryObject<Commylog> listCommylog(@ApiIgnore CommylogQuery query,HttpServletRequest request,Model model){
		String ip=request.getRemoteAddr();
		String userID=query.getSearchUserID();
		if(null==userID || "".equals(userID)) {
			LoginAuthUser u=LoginAuthUser.getUser(request);
			query.setSearchUserID(u.getEntityID());
		}
		if(null!=request.getParameter("type") && !"".equals(request.getParameter("type"))){
			Integer type=Integer.valueOf(request.getParameter("type"));
			Date d=new Date(); 
		    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); 
		    Calendar c = Calendar.getInstance();
		    c.setTime(d);
		    String endTime="";
		    String beginTime="";
			if(type==0) {//查询最近一周的
				endTime=df.format(d);
				c.add(Calendar.DATE, -7);
				beginTime=df.format(c.getTime());
				query.setSearchCreateDateBegin(beginTime);
				query.setSearchCreateDateEnd(endTime);
			}else if(type==1) {//查询本月的
				
				c = Calendar.getInstance();  
		        c.add(Calendar.MONTH, 0);  
		        c.set(Calendar.DAY_OF_MONTH, 1);  
		        beginTime = df.format(c.getTime()); 
				endTime=df.format(d);
				beginTime=df.format(c.getTime());
				query.setSearchCreateDateBegin(beginTime);
				query.setSearchCreateDateEnd(endTime);
			}
		}
		List<Commylog> list = service.listCommylog(query);
		if(null!=list && list.size()>0) {
			for(Commylog c:list) {
			    Map params=new HashMap();
				params.put("groupId", c.getCommylogID());
				String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
				JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
				JSONArray jsonList=json.getJSONArray("resultList");
				List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
				for(AttachementBean att:ab) {
					att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
					if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
						att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
					}else {
						att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
					}
				}
				c.setFileList(ab);
			}
		}
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	@PostMapping("/deleteCommylog")
	@ApiOperation(value = "批量工作日志删除", notes ="删除工作日志")
	public JsonObject<Object> deleteCommylog(@ApiParam(value = "commylogIDs", required = true) @RequestParam("ids") String[] ids , HttpServletRequest request){
		LoginAuthUser u=LoginAuthUser.getUser(request);
		service.deleteCommylog(ids);
		AuditLog auditLog = new AuditLog();
		String operateContent = "ids = {" + Arrays.toString(ids) + "}";
		auditLog.setOperateType("Delete");
		auditLog.setModuleName("工作日志");
		auditLog.setOperateName("删除");
		auditLog.setOperateTime(new Date());
		auditLog.setOperateUserId(u.getEntityID());
		auditLog.setOperateUserName(u.getName());
		auditLog.setOperateState(AuditLogBean.OPERATE_STATE_SUCCESS);
		auditLog.setOperateIp(IpUtil.getIpAddress(request));
		auditLog.setOperateUrl(request.getRequestURL().toString());
		auditLog.setOperateContent(operateContent);
		auditLogService.addAuditLog(auditLog);
		return JsonSuccessObject.SUCCESS;
	}
	
	@PostMapping("/updateCommylog")
	@ApiOperation(value = "工作日志更新", notes ="日志更新")
	public JsonObject<Object> updateCommylog(Commylog obj,HttpServletRequest request) {
		service.updateCommylog(obj);
		LoginAuthUser u=LoginAuthUser.getUser(request);
		String operateContent = "commylogID=" + obj.getCommylogID() + ",commylogValue=" + obj.getCommylogValue()
		+ ",createDate=" + obj.getCreateDate();
		AuditLog auditLog = new AuditLog();
		auditLog.setOperateType("Update");
		auditLog.setModuleName("工作日志"); 
		auditLog.setOperateName("更新");
		auditLog.setOperateTime(new Date());
		auditLog.setOperateUserId(u.getEntityID());
		auditLog.setOperateUserName(u.getUserName());
		auditLog.setOperateState(AuditLogBean.OPERATE_STATE_SUCCESS);
		auditLog.setOperateIp(IpUtil.getIpAddress(request));
		auditLog.setOperateUrl(request.getRequestURL().toString());
		auditLog.setOperateContent(operateContent);
		auditLogService.addAuditLog(auditLog);
		return JsonSuccessObject.SUCCESS;
	}
	
	@GetMapping("/{id}")
	@ApiOperation(value = "根据主键查询工作日志", notes ="工作日志详情")
	public JsonSuccessObject<Commylog> getCommylog(@ApiParam(value="commylogID",required=false) @PathVariable("id") String id){
		Commylog obj = service.getCommylog(id);
		Map params=new HashMap();
		params.put("groupId", obj.getCommylogID());
		String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
		JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
		JSONArray jsonList=json.getJSONArray("resultList");
		List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
		for(AttachementBean att:ab) {
			att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
			if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
				att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
			}else {
				att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
			}
		}
		obj.setFileList(ab);
		JsonSuccessObject<Commylog> returnResult = new JsonSuccessObject<>(obj);
		return returnResult;
	}
}